package Webpacus::Model::Databases;

use strict;
use warnings;
use base 'Catalyst::Model';
use Encode qw/decode/;

=head1 NAME

Webpacus::Model::Databases - Catalyst Model to represent available databases

=head1 SYNOPSIS

See L<Webpacus>

=head1 DESCRIPTION

Get databases from config

=cut

sub new {
	my ( $self, $c, $config ) = @_;

	$self = $self->NEXT::new($c, $config);
	$self->config($config);

	# get databases from config
	$self->{databases} = $c->config->{databases} or
		$c->log->fail("didn't find databases in config");
	$self->{log} = $c->log;

	$self->{config_encoding} = $c->config->{config_encoding} and
		$c->log->debug("using config encoding ", $self->{config_encoding});

	return $self;
}

=head1 convert

Convert encodings from C<config_encoding>

  my $utf8 = $self->convert('foobar');

=cut

sub convert {
	my $self = shift;
	my $val = shift || return;
	my $encoding = $self->{config_encoding} || return $val;
	return decode($encoding, $val);
}

=head1 list_inputs

Returns list of databases with C<input>, C<name>, C<prefix> defined in
Webpacus configuration file C<config.yml> under C<databases>

  my @dbs = $c->comp('Model::Databases')->list_inputs;

=cut

sub list_inputs {
	my $self = shift;

	my @databases;

	# convert to resonable format for TT
	foreach my $db (keys %{ $self->{databases} }) {
		my $d = $self->{databases}->{$db} || die;
		my $inputs = $d->{input} || next;
		$inputs = [ $inputs ] if (ref($inputs) ne 'ARRAY');

		foreach my $i ( @{ $inputs } ) {
			my $el = {
				input	=> $self->convert( $i->{name} ),
				name	=> $self->convert( $d->{name} || $d ),
				prefix	=> $self->convert( $db . '/' . $i->{name} ),
			};
			push @databases, $el;
		}
	}

	return @databases;
}

=head1 list

Returns just of just unique databases with C<name> and C<prefix>.

 my @dbs = $c->comp('Model::Databases')->list;

You can also return just databases that have C<input> defined (that are not
empty databases used for agregation) if you add option C<require_input>.

 my @db_2 = $c->comp('Model::Databases')->list( require_input => 1 );

=cut

sub list {
	my $self = shift;

	my $args = shift;

	my @databases;

	foreach my $db (keys %{ $self->{databases} }) {
		my $d = $self->{databases}->{$db} || die;

		if ($args->{require_input}) {
			next unless ($d->{input});
		}

		my $el = {
			name	=> $self->convert( $d->{name} || $db ),
			prefix	=> $self->convert( $db ),
		};
		push @databases, $el;
	}

	return @databases;
}

=head1 AUTHOR

Dobrica Pavlinusic, C< <<dpavlin@rot13.org>> >

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
